// 引用axios
// import { getCookie } from "../tools/Cookie";
import axios from 'axios'
import config from '../../public/js/config'
// var axios = require("axios");
let href = window.location.href.split("&")
let token
for (let i = 0; i < href.length; i++) {
    if (href[i].indexOf("token=") != -1 && href[i].indexOf("#/") != -1) {
        var tokens = href[i].split("=")[1]
        token = tokens.split("#")[0]
    } else if (href[i].indexOf("token=") != -1) {
        token = href[i].split("=")[1]
    }
}

// 自定义判断元素类型JS
function toType (obj) {
    return {}.toString
        .call(obj)
        .match(/\s([a-zA-Z]+)/)[1]
        .toLowerCase()
}

// 参数过滤函数
function filterNull (o) {
    if (typeof o !== "string") {
        for (var key in o) {
            if (o[key] === null) {
                delete o[key]
            }
            if (toType(o[key]) === "string") {
                o[key] = o[key].trim()
            } else if (toType(o[key]) === "object") {
                o[key] = filterNull(o[key])
            } else if (toType(o[key]) === "array") {
                o[key] = filterNull(o[key])
            }
        }
    }
    return o
}
/*
  接口处理函数
  这个函数每个项目都是不一样的
  需要根据接口的参数进行调整。参考说明文档地址：
  https://cnodejs.org/topic/5378720ed6e2d16149fa16bd
  主要是，不同的接口的成功标识和失败提示是不一致的。
  另外，不同的项目的处理方法也是不一致的，这里出错就是简单的alert
*/
function apiAxios (
    method,
    url,
    params,
    headersOpt = {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
    },
    type
) {
    if (params) {
        params = filterNull(params)
    }
    var headers = {}
    var defHeaders = {
        satoken: sessionStorage.getItem("token")
        // getCookie("token")
    }
    if (type == "crossGet") {
        headers = Object.assign({}, headersOpt)
    } else {
        headers = Object.assign({}, headersOpt, defHeaders)
    }
    // if (type == "jsonDelete") {
    //     var x =
    //         method === "POST" || method === "PUT" || method === "DELETE"
    //             ? params
    //             : null;
    //     var y = method === "GET" ? params : null;
    // } else {

    // }
    var x = method === "POST" || method === "PUT" ? params : null
    var y = method === "GET" || method === "DELETE" ? params : null
    // if (!headers) {
    //     var headers = {
    //         "Content-Type": "application/json;charset=UTF-8"
    //       };
    // }
    return new Promise((resolve, reject) => {
        axios({
            method: method,
            headers: headers,
            url: config.base_url + url,
            data: x,
            params: y,
            withCredentials: false
        })
            .then(function (res) {
                if (res.status == 200) {
                    resolve(res.data)
                } else {
                    console.log(res)
                }
            })
            .catch(function (err) {
                reject(err)
            })
    })
}
function apiAxios1 (
    method,
    url,
    params,
    { headers = { "Content-Type": "application/json;charset=UTF-8" } } = {},
    CancelToken
) {
    if (params) {
        params = filterNull(params)
    }
    var defHeaders = {
        satoken: sessionStorage.getItem("token")
        // getCookie("token")
    }
    // if (!headers) {
    //     var headers = {
    //         "Content-Type": "application/json;charset=UTF-8"
    //       };
    // }
    return new Promise((resolve, reject) => {
        axios({
            method: method,
            headers: Object.assign(defHeaders, headers),
            url: config.base_url + url,
            data: method === "POST" || method === "PUT" ? params : null,
            params: method === "GET" || method === "DELETE" ? params : null,
            withCredentials: false,
            CancelToken: CancelToken
        })
            .then(function (res) {
                if (res.status == 200) {
                    resolve(res.data)
                } else {
                    console.log(res)
                }
            })
            .catch(function (err) {
                reject(err)
            })
    })
}
// 返回在vue模板中的调用接口
export default {
    CancelToken: axios.CancelToken,
    get: function (url, params, headers, type) {
        return apiAxios("GET", url, params, headers, type)
    },
    post: function (url, params, headers) {
        return apiAxios("POST", url, params, headers)
    },
    post2: function (url, params, headers) {
        return apiAxios1("POST", url, params, headers)
    },
    put: function (url, params, headers) {
        return apiAxios("PUT", url, params, headers)
    },
    delete: function (url, params, headers) {
        return apiAxios("DELETE", url, params, headers)
    },
    getTime: function (url, params, headers, CancelToken) {
        return apiAxios1("GET", url, params, headers, CancelToken)
    },
    crossGet: function (url, params) {
        return apiAxios(
            "GET",
            url,
            params,
            {
                "Content-Type":
                    "application/x-www-form-urlencoded;charset=utf-8"
            },
            "crossGet"
        )
    },
    get2: function (url, params, headers) {
        // 特殊的get请求，公共相应参数为token\systemkey,私有参数转string后放data中
        // url = `${url}?token=${config.token}&systemkey=${config.systemkey}`
        url = `${url}?token=${token}`
        params = {
            data: JSON.stringify(params) // 私有参数统一放data中：嵌套的data懒得在外部拼就直接在这处理了
        }
        return apiAxios("GET", url, params, headers)
    }
}
